package algorithms.bloom;

import storage.*;
import configuration.Configuration;

/**
 * @author Nodirjon Siddikov
 */
public class LocalCacheBlock {
	private int _size;
	private int _clk; // maintains the clock tick since last reference of cache
						// block
	private boolean _isOriginal; // when the disk block is retrieved from the
									// server, it is marked as original
	private boolean _isAlive;
	private int _lifetime;
	private Block _diskBlock; // pointer to the disk block
	// constructor

	public LocalCacheBlock(Block block, boolean isOriginal) {
		_diskBlock = block;
		_size = _diskBlock.getSize() + Configuration.tagSize;
		_clk = 0;
		_isOriginal = isOriginal;
		_lifetime = Configuration.localCacheBlockLifeTime * (-1);
		_isAlive = true; // dead cache block are never created
	}

	// get disk block ID
	public int getDiskBlockID() {
		return _diskBlock.getID();
	}

	// gets the disk block
	public Block getDiskBlock() {
		return _diskBlock;
	}

	// gets the current clock count
	public int getClock() {
		return _clk;
	}

	// reset the clock of cache block to 0
	public void resetClock() {
		_clk = 0;
	}

	// decrement the clock
	public void decrementClock() {
		// decrement by 1
		_clk--;
		// if the clock is less than the lifetime
		if (_clk < _lifetime) {
			// cache block becomes DEAD
			if (_isAlive) {
				_isAlive = false; // becomes dead
				if (Configuration.detailedStats != 0) {
					System.out.println("Disk block " + this.getDiskBlockID()
							+ " is now dead.");
				}
			}
			// all dead blocks are considered as non-original block
			if (_isOriginal) {
				// becomes non-original
				_isOriginal = false;
			}
		}
	}

	// get the string representation of cache block
	public String toString() {
		return "CacheBlock : " + _diskBlock.getContent();
	}

	// check if the block is original
	public boolean isOriginal() {
		return _isOriginal;
	}

	// set the cache block as original or copy (i.e. non-original)
	public void setOriginal(boolean value) {
		_isOriginal = value;
	}

	// check if a block is alive
	public boolean isAlive() {
		return _isAlive;
	}

	// get the size of the cache block
	public int getSize() {
		return _size;
	}
}